package io.shdxhl.simplerpc.client.proxy;

import io.shdxhl.simplerpc.client.request.SimpleRequestManager;
import io.shdxhl.simplerpc.code.bean.SimpleBeanFactory;
import io.shdxhl.simplerpc.code.netty.request.RpcRequest;
import io.shdxhl.simplerpc.code.netty.response.RpcResponse;
import io.shdxhl.simplerpc.code.utils.SnowflakeIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * Cglib代理的回调
 */
@Slf4j
public class CglibProxyCallBackHandler implements MethodInterceptor {
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        log.info("CglibProxyCallBackHandler 代理调用拦截：method={}", method.getName());
        String requestId =String.valueOf(SnowflakeIdUtil.getInstance().nextId()) ;
        String className = method.getDeclaringClass().getName();
        String methodName = method.getName();
        Class<?>[] parameterTypes = method.getParameterTypes();
        RpcRequest request = RpcRequest.builder()
                .requestId(requestId)
                .className(className)
                .methodName(methodName)
                .parameterTypes(parameterTypes)
                .parameters(objects).build();

        //发送请求获取响应 response
        SimpleRequestManager requestManager = SimpleBeanFactory.getBean(SimpleRequestManager.class);
        if(Objects.nonNull(requestManager)){
            RpcResponse response = requestManager.sendRequest(request);
            return response.getResult();
        }
        return null;
    }
}
